package com.easonji.attendance.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.easonji.admin.manager.UserManager;
import com.easonji.attendance.mapper.OvertimeMapper;
import com.easonji.attendance.mapper.OvertimeStateMapper;
import com.easonji.attendance.model.Overtime;
import com.easonji.attendance.model.OvertimeState;
import com.easonji.attendance.query.OvertimeVerifyQuery;
import com.easonji.attendance.service.IOvertimeService;
import com.easonji.attendance.service.IOvertimeStateService;
import com.easonji.common.base.query.BaseQuery;
import com.easonji.common.base.service.AbstractBaseService;
import com.easonji.common.factory.PageFactory;
import com.easonji.common.page.PageInfo;
import com.easonji.common.util.JsonUtils;
import com.easonji.common.util.StringUtils;
import com.easonji.core.exception.BizException;
import com.easonji.core.shiro.ShiroUser;
import com.easonji.core.shiro.util.ShiroUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 加班 服务实现类
 * </p>
 *
 * @author easonji
 * @since 2018-09-27
 */
@Service
public class OvertimeServiceImpl extends AbstractBaseService<Overtime> implements IOvertimeService {

    @Resource
    private OvertimeMapper overtimeMapper;

    @Resource
    private UserManager userManager;

    @Resource
    private OvertimeStateMapper overtimeStateMapper;

    @Resource
    private IOvertimeStateService overtimeStateService;




    @Override
    protected JSONObject warp2Json(Overtime overtime) {
       JSONObject result = JsonUtils.parseObject(overtime);
       result.put("otUserName",userManager.getUserNameById(overtime.getOtUser()));
       result.put("otStateName",getStateName(overtime.getOtState()));
       result.put("otStrDate",overtime.getOtStrDate().substring(0,19));
       result.put("otEndDate",overtime.getOtEndDate().substring(0,19));
       return result;
    }


    @Override
    public Object queryList(BaseQuery baseQuery){

        // 分页信息
        Page<Overtime> page = new PageFactory<Overtime>().defaultPage();
        // 查询条件
        Wrapper<Overtime> wrapper = new EntityWrapper<>();



        String beginTime = baseQuery.getBeginTime();
        if (StringUtils.isNotEmpty(beginTime)) {
            wrapper.ge("ot_str_date", beginTime);
        }
        String endTime = baseQuery.getEndTime();
        if (StringUtils.isNotEmpty(endTime)) {
            wrapper.le("ot_str_date", endTime);
        }

        ShiroUser shiroUser = ShiroUtils.getUser();
        //查询本人创建的和上级为本人创建的单子
        wrapper.and("(ot_user ={0} or ot_create_user={0})",shiroUser.getUserId());

        wrapper.orderBy("ot_id",false);

        List<Overtime> overtimes = overtimeMapper.selectPage(page, wrapper);

        return new PageInfo(warp(overtimes), page.getTotal());
    }

    @Override
    public Object queryVerifyList(OvertimeVerifyQuery overtimeVerifyQuery){

        ShiroUser shiroUser = ShiroUtils.getUser();



        // 分页信息
        Page<Overtime> page = new PageFactory<Overtime>().defaultPage();
        // 查询条件
        Wrapper<Overtime> wrapper = new EntityWrapper<>();

        String beginTime = overtimeVerifyQuery.getBeginTime();
        if (StringUtils.isNotEmpty(beginTime)) {
            wrapper.ge("ot_str_date", beginTime);
        }
        String endTime = overtimeVerifyQuery.getEndTime();
        if (StringUtils.isNotEmpty(endTime)) {
            wrapper.le("ot_str_date", endTime);
        }

        //如果是2则查 历吏审核的
        if(overtimeVerifyQuery.getState()!=null && overtimeVerifyQuery.getState()==2){
            List<Integer> oids = overtimeStateService.queryOvertimeIdByauditor(shiroUser.getUserId()); //查询历吏审核的 ID
            if(oids.size()==0){
                wrapper.eq("ot_id",0);
            }else{
                wrapper.in("ot_id",oids);
            }

        }else{
            wrapper.eq("ot_next_auditor",shiroUser.getUserId());
        }



        wrapper.orderBy("ot_id",false);

        List<Overtime> overtimes = overtimeMapper.selectPage(page, wrapper);



        return new PageInfo(warp(overtimes), page.getTotal());
    }

    @Override
    public Object queryRowById(Integer otId) {
        Overtime overtime = overtimeMapper.selectById(otId);
        return warp(overtime);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = BizException.class)
    public Integer save(Overtime overtime,List<Map<String,Integer>> Auditors) {

        Integer insertint = overtimeMapper.insert(overtime);
        if(insertint==0){
            return 0;
        }

        //保存申请状态 state  0 等待审核  1审核通过  -1审核失败
        OvertimeState overtimeState = new OvertimeState();
        overtimeState.setOtsAuditor(overtime.getOtCreateUser());
        overtimeState.setOtsDatetime(new Date());
        overtimeState.setOtsOvertime(overtime.getOtId());
        overtimeState.setOtsState(1);

        insertint = overtimeStateMapper.insert(overtimeState);
        if(insertint==0){
            return 0;
        }

        for(Map<String,Integer> map : Auditors){
            overtimeState = new OvertimeState();
            overtimeState.setOtsAuditor(map.get("user"));
            overtimeState.setOtsPost(map.get("post"));
            overtimeState.setOtsOvertime(overtime.getOtId());
            overtimeState.setOtsState(0);
            insertint = overtimeStateMapper.insert(overtimeState);
            if(insertint==0){
                return 0;
            }
        }


        return insertint;
    }

    @Override
    public Integer update(Overtime overtimeForm) {

        ShiroUser shiroUser = ShiroUtils.getUser();
        Overtime overtime = new Overtime();
        overtimeForm.setOtUpdateUser(shiroUser.getUserId());
        overtimeForm.setOtUpdateDate(new Date());
        BeanUtils.copyProperties(overtimeForm,overtime);
        return overtimeMapper.updateById(overtime);
    }

    @Override
    public Integer delete(Integer otId) {
        Wrapper<Overtime> wrapper = new EntityWrapper<>();
        wrapper.eq("ot_id", otId);
        return overtimeMapper.delete(wrapper);
    }

    private String getStateName(Integer state){
        String stateName = null;

        if(state == null){
            return "";
        }
        switch(state){
            case 0:
                stateName = "申请成功，等待审核";
                break;
            case 1:
                stateName = "线长审核通过，等待主管审核";
                break;
            case 2:
                stateName = "审核通过";
                break;
            case -1:
                stateName = "线长不通过";
                break;
            case -2:
                stateName = "主管不通过";
                break;
            default :
                stateName = "";
        }

        return stateName;
    }

}
